import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
import _objectWithoutProperties from '@babel/runtime/helpers/esm/objectWithoutProperties';
import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';
import { Upload as AntdUpload, Button } from 'antd';
import React, { useState } from 'react';
import { useFieldContext } from '../../contexts/FieldContext';
import createField from '../../createField';
import logger from '../../logger';
import './index.css';
import { convetAccept, fileValidatorFactory } from './utils';
var _excluded = ['fileName', 'max', 'fileList', 'onChange', 'beforeUpload', 'children'];
var Upload = function Upload(_ref) {
  var fileName = _ref.fileName,
    max = _ref.max,
    fileList = _ref.fileList,
    onChange = _ref.onChange,
    beforeUploadProp = _ref.beforeUpload,
    children = _ref.children,
    rest = _objectWithoutProperties(_ref, _excluded);
  var _useFieldContext = useFieldContext(),
    name = _useFieldContext.name;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    loading = _useState2[0],
    setLoading = _useState2[1];
  var defaultTransformFile = rest.watermark
    ? function (file) {
        return new Promise(function (resolve) {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = function () {
            var canvas = document.createElement('canvas');
            var img = document.createElement('img');
            img.src = reader.result;
            img.onload = function () {
              var ctx = canvas.getContext('2d');
              if (!ctx) return;
              ctx.drawImage(img, 0, 0);
              ctx.fillStyle = 'red';
              ctx.textBaseline = 'middle';
              ctx.fillText(rest.watermark, 20, 20);
              // @ts-ignore
              canvas.toBlob(resolve);
            };
          };
        });
      }
    : undefined;
  var transformFile = rest.transformFile ? rest.transformFile : defaultTransformFile;
  var beforeUpload = fileValidatorFactory(rest); // 上传前校验
  var handleChange = function handleChange(info) {
    if (info.file.status === 'uploading') {
      setLoading(true);
      onChange && onChange(info);
      return;
    }
    if (info.file.status === 'done') {
      setLoading(false);
      if (info.file.response && info.file.response.success) {
        logger.success('上传成功');
      } else {
        logger.fail(
          '\u4E0A\u4F20\u5931\u8D25\uFF0C'.concat(
            info.file.response.errorMsg || info.file.response.errorMessage,
          ),
        );
      }
    } else if (info.file.status === 'error') {
      setLoading(false);
      logger.fail(
        '\u4E0A\u4F20\u5931\u8D25\uFF0C'.concat(
          info.file.response.errorMsg || info.file.response.errorMessage,
        ),
      );
    } else {
      setLoading(false);
    }
    info.fileList = info.fileList.filter(function (file) {
      if (
        file.status === 'error' ||
        file.uploadPrevented ||
        (file.status === 'done' && file.response && !file.response.success)
      )
        return false;
      return true;
    });
    if (onChange) onChange(info);
  };
  /**
   * listType 为 'picture-card' 时展示上传图片框
   * 其他展示上传按钮
   */
  var uploadBtn = children
    ? children
    : rest.listType == 'picture-card'
    ? /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'szaf-upload-picture',
        },
        /*#__PURE__*/ React.createElement(PlusOutlined, {
          className: 'szaf-upload-picture-icon',
        }),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'ant-upload-text',
          },
          '\u4E0A\u4F20\u56FE\u7247',
        ),
      )
    : /*#__PURE__*/ React.createElement(
        Button,
        {
          type: 'default',
        },
        loading
          ? /*#__PURE__*/ React.createElement(LoadingOutlined, {
              className: 'szaf-upload-icon',
            })
          : /*#__PURE__*/ React.createElement(UploadOutlined, {
              className: 'szaf-upload-icon',
            }),
        '\u6587\u4EF6\u4E0A\u4F20',
      );
  return /*#__PURE__*/ React.createElement(
    AntdUpload,
    _objectSpread(
      _objectSpread({}, rest),
      {},
      {
        name: fileName || name,
        fileList: fileList,
        accept: convetAccept(rest.accept),
        transformFile: transformFile,
        beforeUpload: beforeUploadProp ? beforeUploadProp : beforeUpload,
        onChange: handleChange,
      },
    ),
    max != undefined && fileList && fileList.length >= max ? null : uploadBtn,
  );
};
export default createField(Upload, {
  defaultDetailType: 'tag',
  defaultFormItemProps: {
    valuePropName: 'fileList',
    getValueFromEvent: function getValueFromEvent(e) {
      return Array.isArray(e) ? e : e && e.fileList;
    },
  },
});
